package com.mind.common.utils.file;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.mind.common.config.MindConfig;
import com.mind.common.utils.DateUtils;
import com.mind.common.utils.StringUtils;
import com.mind.common.utils.file.vo.FileVo;
import com.mind.common.utils.uuid.IdUtils;
import com.mind.common.utils.uuid.UUID;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.http.MediaType;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * 文件处理工具类
 *
 * @author today
 */
public class FileUtils {
    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
    public static Map<String, String> extensionToBase64PrefixMap = new HashMap<>();

    static {
        // 添加文件后缀名与Base64前缀的关系
        extensionToBase64PrefixMap.put("txt", "data:text/plain;base64,");
        extensionToBase64PrefixMap.put("jpg", "data:image/jpeg;base64,");
        extensionToBase64PrefixMap.put("jpeg", "data:image/jpeg;base64,");
        extensionToBase64PrefixMap.put("Jpeg", "data:image/jpeg;base64,");
        extensionToBase64PrefixMap.put("png", "data:image/png;base64,");
        extensionToBase64PrefixMap.put("gif", "data:image/gif;base64,");
        extensionToBase64PrefixMap.put("html", "data:text/html;base64,");
        extensionToBase64PrefixMap.put("css", "data:text/css;base64,");
        extensionToBase64PrefixMap.put("js", "data:application/javascript;base64,");
        extensionToBase64PrefixMap.put("pdf", "data:application/pdf;base64,");
        extensionToBase64PrefixMap.put("xml", "data:application/xml;base64,");
        extensionToBase64PrefixMap.put("xlsx", "data:application/xlsx;base64,");
        extensionToBase64PrefixMap.put("docx", "data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,");
    }

    /**
     * 字符常量：斜杠 {@code '/'}
     */
    public static final char SLASH = '/';

    /**
     * 字符常量：反斜杠 {@code '\\'}
     */
    public static final char BACKSLASH = '\\';

    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os       输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException {
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            IOUtils.close(os);
            IOUtils.close(fis);
        }
    }

    /**
     * 写数据到文件中
     *
     * @param data 数据
     * @return 目标文件
     * @throws IOException IO异常
     */
    public static String writeImportBytes(byte[] data) throws IOException {
        return writeBytes(data, MindConfig.getImportPath());
    }

    /**
     * 写数据到文件中
     *
     * @param data      数据
     * @param uploadDir 目标文件
     * @return 目标文件
     * @throws IOException IO异常
     */
    public static String writeBytes(byte[] data, String uploadDir) throws IOException {
        FileOutputStream fos = null;
        String pathName = "";
        try {
            String extension = getFileExtendName(data);
            pathName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;
            File file = FileUploadUtils.getAbsoluteFile(uploadDir, pathName);
            fos = new FileOutputStream(file);
            fos.write(data);
        } finally {
            IOUtils.close(fos);
        }
        return FileUploadUtils.getPathFileName(uploadDir, pathName);
    }

    /**
     * 删除文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            flag = file.delete();
        }
        return flag;
    }

    /**
     * 文件名称验证
     *
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename) {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 检查文件是否可下载
     *
     * @param resource 需要下载的文件
     * @return true 正常 false 非法
     */
    public static boolean checkAllowDownload(String resource) {
        // 禁止目录上跳级别
        if (StringUtils.contains(resource, "..")) {
            return false;
        }

        // 检查允许下载的文件规则
        if (ArrayUtils.contains(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType(resource))) {
            return true;
        }

        // 不在允许下载的文件规则
        return false;
    }

    /**
     * 下载文件名重新编码
     *
     * @param request  请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

    /**
     * 下载文件名重新编码
     *
     * @param response     响应对象
     * @param realFileName 真实文件名
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
        String percentEncodedFileName = percentEncode(realFileName);

        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);

        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
        response.setHeader("Content-disposition", contentDispositionValue.toString());
        response.setHeader("download-filename", percentEncodedFileName);
    }

    /**
     * 下载文件名重新编码
     *
     * @param response     响应对象
     * @param realFileName 真实文件名
     */
    public static void setInlineResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
        String percentEncodedFileName = percentEncode(realFileName);

        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("inline;filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);

        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
        response.setHeader("Content-disposition", contentDispositionValue.toString());
        response.setHeader("download-filename", percentEncodedFileName);
        response.setHeader("Content-Type", String.valueOf(MediaType.IMAGE_PNG));
    }

    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+", "%20");
    }

    /**
     * 获取图像后缀
     *
     * @param photoByte 图像数据
     * @return 后缀名
     */
    public static String getFileExtendName(byte[] photoByte) {
        String strFileExtendName = "jpg";
        if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56)
                && ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) {
            strFileExtendName = "gif";
        } else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70)) {
            strFileExtendName = "jpg";
        } else if ((photoByte[0] == 66) && (photoByte[1] == 77)) {
            strFileExtendName = "bmp";
        } else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71)) {
            strFileExtendName = "png";
        }
        return strFileExtendName;
    }

    /**
     * 获取文件名称 /profile/upload/2022/04/16/today.png -- today.png
     *
     * @param fileName 路径名称
     * @return 没有文件路径的名称
     */
    public static String getName(String fileName) {
        if (fileName == null) {
            return null;
        }
        int lastUnixPos = fileName.lastIndexOf('/');
        int lastWindowsPos = fileName.lastIndexOf('\\');
        int index = Math.max(lastUnixPos, lastWindowsPos);
        return fileName.substring(index + 1);
    }

    /**
     * 获取不带后缀文件名称 /profile/upload/2022/04/16/today.png -- today
     *
     * @param fileName 路径名称
     * @return 没有文件路径和后缀的名称
     */
    public static String getNameNotSuffix(String fileName) {
        if (fileName == null) {
            return null;
        }
        String baseName = FilenameUtils.getBaseName(fileName);
        return baseName;
    }

    /**
     * 获取文件的后缀名
     *
     * @param fileUrl
     * @return
     */
    public static String getFileExt(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return "";
        }
        String[] urlArr = fileUrl.split("\\.");
        if (urlArr.length <= 1) {
            return "";
        }
        return urlArr[urlArr.length - 1];
    }

    public static String file2Base64(String filePath) throws IOException {
        // 读取文件的所有字节
        byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));

        // 使用Base64编码字节数组
        byte[] base64Bytes = Base64.getEncoder().encode(fileBytes);

        // 将Base64编码的字节数组转换为字符串
        return extensionToBase64PrefixMap.get(getFileExt(filePath).toLowerCase()) + StandardCharsets.UTF_8.decode(ByteBuffer.wrap(base64Bytes));
    }

    public static List<FileVo> pdfToImage(File file, String basePath, String bucketName) throws IOException {
        PDDocument document = PDDocument.load(file);
        PDFRenderer renderer = new PDFRenderer(document);
        int pages = document.getNumberOfPages();
        List<FileVo> fileVos = new ArrayList<>();
        for (int i = 0; i < pages; i++) {
            BufferedImage image = renderer.renderImageWithDPI(i, 144, ImageType.RGB); // 可以根据需要调整DPI
            FileVo fileVo = getUrl(basePath, bucketName, "png");
            File imageFile = new File(fileVo.getFilePath());
            ImageIO.write(image, "png", imageFile);
            fileVos.add(fileVo);
        }
        document.close();
        return fileVos;
    }

    /**
     * 获取url
     *
     * @param buketName
     * @param ext
     * @return
     */
    public static FileVo getUrl(String basePath, String buketName, String ext) {
        String uuid = UUID.fastUUID().toString(true);
        return new FileVo() {{
            setApiUrl("/api/customer/file/" + buketName + "/" + uuid + "." + ext);
            setFilePath(Paths.get(basePath, uuid + "." + ext).toString());
            setFileName(uuid + "." + ext);
        }};
    }

    public static FileVo download(String fileUrl, String basePath, String bucketName, String fileExt) throws IOException {
        if (StringUtils.isEmpty(fileExt))
            fileExt = FileUtils.getFileExt(fileUrl);
        InputStream inputStream = new URL(fileUrl).openStream();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        int nRead;
        byte[] data = new byte[1024];

        // 读取数据到ByteArrayOutputStream
        while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
        buffer.flush();
        FileVo fileVo = getUrl(basePath, bucketName, fileExt);
        Path path = Paths.get(fileVo.getFilePath());
        File file = new File(path.getParent().toString());
        if (!file.exists()) {
            file.mkdirs();
        }
        fileVo.setSourceUrl(fileUrl);
        Files.write(path, buffer.toByteArray());
        return fileVo;

    }


    public static boolean isDisplay(String fileExt) {
        return Arrays.asList("jpg", "jpeg", "png", "gif", "bmp", "tiff", "pdf").contains(fileExt.toLowerCase());
    }

    public static JSONArray toAssets(List<FileVo> fileVoList) {
        JSONArray list = new JSONArray();
        for (FileVo fileVo : fileVoList) {
            list.add(JSON.toJSONString(fileVo));
        }
        return list;
    }

    public static FileVo toFileVo(JSONObject originFile) {
        FileVo fileVo = new FileVo();
        fileVo.setApiUrl(originFile.getString("apiUrl"));
        fileVo.setSourceUrl(originFile.getString("sourceUrl"));
        fileVo.setFilePath(originFile.getString("filePath"));
        fileVo.setFileName(originFile.getString("fileName"));

        return fileVo;
    }


    public List<String> convertImagesFromPdf(File file) {
//        PDDocument document = PDDocument.load(file);
//        PDFRenderer renderer = new PDFRenderer(document);
//        int pages = document.getNumberOfPages();
//
//        for (int i = 0; i < pages; i++) {
//            BufferedImage image = renderer.renderImageWithDPI(i, 300); // 可以根据需要调整DPI
//            File imageFile = new File("path/to/output/images/page_" + (i + 1) + ".png");
//            ImageIO.write(image, "png", imageFile);
//        }
//        document.close();
        return new ArrayList<>();
    }

    public static void base64ToFile(String base64, String outFile) {
        try {
            for (String fileType : extensionToBase64PrefixMap.values()) {
                base64 = base64.replace(fileType, "");
            }
            byte[] decodedBytes = cn.hutool.core.codec.Base64.decode(base64);
            Files.write(Paths.get(outFile), decodedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
